#!/bin/sh
INSTALL_DIR=/opt/wine-ce
if [ $# -gt 0 ] ; then
    INSTALL_DIR=$1
fi

echo "install directory: $INSTALL_DIR"

ARCH_PLATFORM=$(arch)
QEMU_TARGET_LIST=
BOX64_DYNAREC=
if [ "$ARCH_PLATFORM" = "x86_64" ] || [ "$ARCH_PLATFORM" = "amd64" ]; then
    QEMU_TARGET_LIST="aarch64-linux-user"
elif [ "$ARCH_PLATFORM" = "aarch64" ] || [ "$ARCH_PLATFORM" = "arm64" ]; then
    BOX64_DYNAREC="ARM_DYNAREC"
elif [ "$ARCH_PLATFORM" = "riscv64" ]; then
    BOX64_DYNAREC="RV64_DYNAREC"
    QEMU_TARGET_LIST="aarch64-linux-user"
else
    QEMU_TARGET_LIST="x86_64-linux-user,aarch64-linux-user"
fi

echo "Build Wine"
cd wine
i386_CC="clang -fuse-ld=lld -march=x86-64 --target=i686-pc-windows" \
x86_64_CC="clang -fuse-ld=lld -march=x86-64 --target=x86_64-pc-windows" \
x86_64_UNIX_CC="clang -fuse-ld=lld -march=x86-64 --target=x86_64-pc-linux -I/usr/x86_64-linux-gnu/include" \
aarch64_CC="clang -fuse-ld=lld -march=armv8+lse --target=aarch64-pc-windows" \
aarch64_UNIX_CC="clang -fuse-ld=lld -march=armv8+lse --target=aarch64-pc-linux -I/usr/aarch64-linux-gnu/include" \
./configure --prefix="$INSTALL_DIR" --disable-tests --enable-archs=i386,x86_64,aarch64
make -j$(nproc)
rm -rf $INSTALL_DIR
make install-lib
cd ..

if [ $QEMU_TARGET_LIST ]; then
    echo "Build QEMU"
    rm -rf build.qemu
    mkdir build.qemu && cd build.qemu
    CC=gcc CC_FOR_BUILD="$CC" CXX="$CC" HOST_CC="$CC" CFLAGS="-fPIC" \
    LDFLAGS="-Wl,-Ttext-segment=0x100000000 -Wl,-z,max-page-size=0x1000 -Wl,-Bstatic,-lglib-2.0 -Wl,-Bdynamic,-ldl" \
    ../qemu/configure --without-default-features --disable-fdt --disable-system --enable-ca11c0de --disable-rcu --target-list=$QEMU_TARGET_LIST
    ninja -j$(nproc)
    if [ -e qemu-x86_64 ] ; then
        strip qemu-x86_64 -o "$INSTALL_DIR"/bin/qemu-x86_64
    fi
    if [ -e qemu-aarch64 ] ; then
        strip qemu-aarch64 -o "$INSTALL_DIR"/bin/qemu-aarch64
    fi
    cd ..
fi

if [ $BOX64_DYNAREC ]; then
    echo "Build BOX64"
    rm -rf build.box64
    mkdir build.box64 && cd build.box64
    cmake -D $BOX64_DYNAREC=ON -D CMAKE_POSITION_INDEPENDENT_CODE=ON -D CMAKE_BUILD_TYPE=RelWithDebinfo  ../box64
    make -j$(nproc)
    cp box64 "$INSTALL_DIR"/bin/box64
    cd ..
fi

sh generate_scripts.sh "$INSTALL_DIR"/bin

